from model.todo import ToDo
from utils.common import *
from utils.json_data import JsonData
from playhouse.shortcuts import model_to_dict, dict_to_model
from peewee import SQL


def insert_todo_task(task_desc):
    """
        insert a new todo task
        :return: JsonData, success: code = 200, msg = "insert ok", data = task_id
                           failed: code = 1001, msg = "insert error:" + prompt information, data = {id: value}
    """
    try:
        _result = ToDo.insert(name=task_desc, create_time=get_now_time(), complete_time=None, sign=1).execute()
        return JsonData().success_data(msg="insert ok", data={"id": _result})
    except Exception as e:
        return JsonData().error(code="1001", msg=f"insert error:{e}")


def done_todo_task(todo_id):
    try:
        if len(json_to_dict(select_from_id(todo_id))["data"]) == 0:
            return JsonData().error(code="1002", msg=f"done error:not found this is id")
        _result = ToDo.update(complete_time=get_now_time()).where(ToDo.todo_id == todo_id).execute()
        new_to_old(todo_id)
        return JsonData().success_data(msg="done ok", data={"id": todo_id})
    except Exception as e:
        return JsonData().error(code="1002", msg=f"done error:{e}")


def new_to_old(todo_id):
    try:
        _result = ToDo.update(sign=0).where(todo_id == todo_id).execute()
        return JsonData().success_data(msg="update sign ok", data={"id": todo_id})
    except Exception as e:
        return JsonData().error(code="1003", msg=f"update sign error:{e}")


def set_new(todo_id):
    try:
        _result = ToDo.update(sign=1).where(todo_id == todo_id).execute()
        return JsonData().success_data(msg="update sign ok", data={"id": todo_id})
    except Exception as e:
        return JsonData().error(code="1003", msg=f"update sign error:{e}")


def select_all():
    try:
        _results = ToDo.select()
        _list = list()
        for _res in _results:
            _list.append(model_to_dict(_res))
        return JsonData().success_data(msg="select all ok", data=_list)
    except Exception as e:
        return JsonData().error(code="1004", msg=f"select error:{e}")


def select_from_time(create_time, complete_time):
    try:
        _results = ToDo.select().where((ToDo.create_time <= create_time) & (ToDo.complete_time <= complete_time))
        if complete_time is None:
            _results = ToDo.select().where(ToDo.create_time <= create_time)
        _list = list()
        for _res in _results:
            _list.append(model_to_dict(_res))
            # 如果创建时间大于1天或者已完成的，取消new状态, 否则为new
            created_time = get_format_time_to_now_second(model_to_dict(_res)["create_time"])
            if created_time < day and model_to_dict(_res)["complete_time"] is None:
                if get_json_code(set_new(model_to_dict(_res)["todo_id"])) != "200":
                    print("update sign to new failed")
            else:
                if get_json_code(new_to_old(model_to_dict(_res)["todo_id"])) != "200":
                    print("update sign to old failed")
        return JsonData().success_data(msg="select condition ok", data=_list)
    except Exception as e:
        return JsonData().error(code="1004", msg=f"select error:{e}")


def select_from_time_split(create_time, complete_time):
    try:
        complete_results = ToDo.select().where((ToDo.create_time <= create_time)
                                               & (ToDo.complete_time <= complete_time)
                                               & (ToDo.complete_time != None))
        incomplete_results = ToDo.select().where((ToDo.create_time <= create_time) &
                                                 (ToDo.complete_time <= complete_time)
                                                 & (ToDo.complete_time == None))
        if complete_time is None:
            complete_results = _results = ToDo.select().where((ToDo.create_time <= create_time) &
                                                              (ToDo.complete_time != None))
            incomplete_results = _results = ToDo.select().where((ToDo.create_time <= create_time) &
                                                              (ToDo.complete_time == None))
        _list_complete = list()
        for _res in complete_results:
            _list_complete.append(model_to_dict(_res))
        _list_incomplete = list()
        for _res in incomplete_results:
            _list_incomplete.append(model_to_dict(_res))
        _dict = {
            "complete": _list_complete,
            "incomplete": _list_incomplete
        }
        return JsonData().success_data(msg="select condition ok", data=_dict)
    except Exception as e:
        return JsonData().error(code="1004", msg=f"select error:{e}")


def get_record_number():
    return ToDo.select().count()


def select_from_id(task_id):
    try:
        _results = ToDo.select().where(ToDo.todo_id == task_id)
        _list = list()
        for _res in _results:
            _list.append(model_to_dict(_res))
        if len(_list) == 0:
            return JsonData().error(code="1004", msg=f"select id error: not found this id")
        return JsonData().success_data(msg="select id ok", data=_list)
    except Exception as e:
        return JsonData().error(code="1004", msg=f"select error:{e}")


def select_from_sql(sql, cls="*"):
    """
    Query with SQL statement
    :param sql:where sql
    :param cls: some column name
    """
    try:
        _results = ToDo.select(SQL(cls)).where(SQL(sql))
        _list = list()
        for _res in _results:
            _list.append(model_to_dict(_res))
        return JsonData().success_data(msg="select sql ok", data=_list)
    except Exception as e:
        return JsonData().error(code="1004", msg=f"select error:{e}")

